package com.example.photo_sharing.page.userInfo;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.os.NetworkOnMainThreadException;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.photo_sharing.R;
import com.example.photo_sharing.global.App;
import com.example.photo_sharing.entity.User;
import com.example.photo_sharing.tool.Impl.PhotoImpl;
import com.example.photo_sharing.tool.Impl.UserInfoSPImpl;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeInfo extends AppCompatActivity {

    private App app;
    private PhotoImpl pt = new PhotoImpl();

    private SharedPreferences sharedPreferences;
    private UserInfoSPImpl usp;

    private ImageView img;
    private int sex = 0;
    private String tempAvatarUrl;

    private int REQUEST_IMAGE_OPEN = 2;
    private int REQUEST_MANAGER_PERMISSION = 3;
    private int REQUEST_CODE_CAMERA = 4;

    private TextView text1;
    private RadioButton rbt0;
    private RadioButton rbt1;
    private RadioButton rbt2;
    private EditText text3;
    private EditText text4;

    private String path = "/storage/emulated/0/DCIM/";

    //底部弹窗
    private BottomSheetDialog bottomSheetDialog;
    //弹窗视图
    private View bottomView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_info);

        requestManagerPermission();
        requestCameraPermission();

        app = (App)getApplication();

        sharedPreferences = getSharedPreferences("userInfo",MODE_PRIVATE);
        usp = new UserInfoSPImpl(sharedPreferences);

        //隐藏标题栏
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide(); //隐藏标题栏
        }

        img = findViewById(R.id.change_avatar);
        text1 = findViewById(R.id.change_userId);
        //EditText text2 = findViewById(R.id.change_sex);
        rbt0 = findViewById(R.id.rbt_0);
        rbt1 = findViewById(R.id.rbt_1);
        rbt2 = findViewById(R.id.rbt_2);
        text3 = findViewById(R.id.change_introduce);
        text4 = findViewById(R.id.change_username);

        User user = usp.getInfo();
        tempAvatarUrl = user.getAvatar();
        Picasso.get().load(user.getAvatar()).into(img);
        text1.setText(user.getUserId()+" ");
        //text2.setText(user.getSex()+"");
        sex = user.getSex();
        switch (sex){
            case 1:
                rbt1.setChecked(true);
                break;
            case 2:
                rbt2.setChecked(true);
                break;
            default:
                rbt0.setChecked(true);
                break;
        }
        text3.setText(user.getIntroduce());
        text4.setText(user.getUsername());

        //跟新用户信息
        Button btn = findViewById(R.id.change_save);
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                String introduce = text3.getText().toString();
                //int sex = Integer.parseInt(text2.getText().toString());
                String userId = text1.getText().toString();

                String avatar = tempAvatarUrl;

                String username = text4.getText().toString();
                System.out.println(introduce+" "+sex+" "+userId+" "+avatar+" "+username);
                post(introduce,sex,userId,avatar,username);
                usp.saveInfo(introduce,sex,userId,avatar,username);
            }
        });

        //添加更换头像的功能
        img.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){


                bottomSheetDialog = new BottomSheetDialog(view.getContext());
                bottomView = getLayoutInflater().inflate(R.layout.activity_change_info_avatar_button, null);
                bottomSheetDialog.setContentView(bottomView);
                TextView tvTakePictures = bottomView.findViewById(R.id.changeAvatar_take_pictures);
                TextView tvOpenAlbum = bottomView.findViewById(R.id.changeAvatar_open_album);
                TextView tvCancel = bottomView.findViewById(R.id.changeAvatar_cancel);

                //拍照
                tvTakePictures.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        File file = new File(path);
                        if (!file.exists()) {
                            file.mkdir();
                        }
                        String fileName = setImgName() + ".jpg"; //图片的文件名
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        Uri photoUri = Uri.fromFile(new File(path + fileName));//记录图片的uri
                        FileProvider.getUriForFile(getApplicationContext(),getPackageName() + ".fileprovider",file);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); //photoUri就是图片存储的位置

                        System.out.println("asdasdjaiosjdioa"+ photoUri);

                        startActivityForResult(intent, REQUEST_CODE_CAMERA);

                        System.out.println("131232");
                        bottomSheetDialog.cancel();
                    }
                });
                //打开相册
                tvOpenAlbum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ImageView imgView = null;  //用于显示图片
                        //打开相册
                        Intent intent = new  Intent(Intent.ACTION_PICK);
                        //指定获取的是图片
                        intent.setType("image/*");
                        //startActivityForResult()方法有两个参数，第一个参数为Intent，第二个参数为自定义的一个请求码，这个请求码会在onActivityResult()方法中被返回。
                        startActivityForResult(intent, REQUEST_IMAGE_OPEN);
                        bottomSheetDialog.cancel();

                    }
                });
                //取消
                tvCancel.setOnClickListener(v -> {
                    bottomSheetDialog.cancel();
                });

                bottomSheetDialog.show();
            }
        });
        //设置性别的排他选择
        rbt0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rbt1.setChecked(false);
                rbt2.setChecked(false);
                sex = 0;
            }
        });

        //设置性别的排他选择
        rbt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rbt0.setChecked(false);
                rbt2.setChecked(false);
                sex = 1;
            }
        });

        //设置性别的排他选择
        rbt2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rbt1.setChecked(false);
                rbt0.setChecked(false);
                sex = 2;
            }
        });
    }

    private void post(String introduce,int sex,String userId,String avatar,String username){
        new Thread(() -> {

            // url路径
            String url = "http://47.107.52.7:88/member/photo/user/update";

            // 请求头
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("appId", app.getAppId())
                    .add("appSecret", app.getAppSecret())
                    .add("Content-Type", "application/json")
                    .build();

            // 请求体
            // PS.用户也可以选择自定义一个实体类，然后使用类似fastjson的工具获取json串
            Map<String, Object> bodyMap = new HashMap<>();
            bodyMap.put("introduce", introduce);
            bodyMap.put("sex", sex);
            bodyMap.put("avatar", avatar);
            bodyMap.put("id", userId);
            bodyMap.put("username", username);
            // 将Map转换为字符串类型加入请求体中
            String body = JSON.toJSONString(bodyMap);

            MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");

            //请求组合创建
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .post(RequestBody.create(MEDIA_TYPE_JSON, body))
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }

    /**
     * 回调
     */
    private final Callback callback = new Callback() {
        @Override
        public void onFailure(@NonNull Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
        }
        @Override
        public void onResponse(@NonNull Call call, Response response) throws IOException {
            //TODO 请求成功处理
            String responseData = response.body().string();
            System.out.println(responseData);
            int code = JSONObject.parseObject(responseData).getInteger("code");
            if(code == 200){
                Looper.prepare();
                Toast.makeText(ChangeInfo.this,"修改成功",Toast.LENGTH_LONG).show();
                Looper.loop();
            }
            else{
                Looper.prepare();
                Toast.makeText(ChangeInfo.this,"修改失败",Toast.LENGTH_LONG).show();
                Looper.loop();
            }
        }
    };

    //申请文件管理权限
    private void requestManagerPermission() {
        //当系统在11及以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 没文件管理权限时申请权限
            if (!Environment.isExternalStorageManager()) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_MANAGER_PERMISSION);
            }
        }

    }

    private void requestCameraPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_CAMERA);
            return;
        }
    }


    private   String  setImgName(){

        Date  date =new Date(System.currentTimeMillis( ));

        SimpleDateFormat   dateFormat=new SimpleDateFormat("yyyyMMdd_HHmmss");

        return "IMG_"+dateFormat.format(date);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //将选择的图片显示
        if(requestCode == REQUEST_IMAGE_OPEN && resultCode == Activity.RESULT_OK &&data !=null){
            Uri uri = data.getData();
            System.out.println(data+"");
            System.out.println(uri+"");
            //Bitmap bitmap = null;
            String ava_url = pt.uploadAvatar(uri,this);
            Picasso.get().load(ava_url).into(img);
            tempAvatarUrl = ava_url;
            //Uri转化为Bitmap
            /*try {
                bitmap = pt.getBitmapFromUri(uri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            img.setImageBitmap(bitmap);*/

        }
        else if (resultCode == REQUEST_CODE_CAMERA) {
            System.out.println("相机666");
        }
        else if (requestCode == REQUEST_MANAGER_PERMISSION && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            //用户拒绝权限，重新申请
            if (!Environment.isExternalStorageManager()) {
                requestManagerPermission();
            }
        }
        else if (requestCode == REQUEST_CODE_CAMERA && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            //用户拒绝权限，重新申请
            if (!Environment.isExternalStorageManager()) {
                requestCameraPermission();
            }
        }
        else{
            System.out.println("相机669996");
        }

    }

}
